package cn.com.idmy.auth.interceptor;

import cn.com.idmy.auth.router.StopMatchException;
import cn.com.idmy.base.annotation.Whitelist;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.dromara.hutool.core.annotation.AnnotationUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.function.Consumer;

@Accessors(fluent = true)
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
    protected final Consumer<Object> auth;
    @Setter
    protected boolean whitelistEnabled = true;

    @Nullable
    protected static <T extends Annotation> T getAnnotation(Method method, Class<? extends Annotation> annotationClass) {
        Annotation annotation = AnnotationUtil.getAnnotation(method, annotationClass);
        if (annotation == null) {
            return (T) AnnotationUtil.getAnnotation(method.getDeclaringClass(), annotationClass);
        } else {
            return (T) annotation;
        }
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        if (handler instanceof HandlerMethod method) {
            if (hasAuthWhitelist(method.getMethod())) {
                return true;
            }
        }
        try {
            auth.accept(handler);
        } catch (StopMatchException ignored) {
        }
        return true;
    }

    protected boolean hasAuthWhitelist(Method method) {
        Whitelist at = getAnnotation(method, Whitelist.class);
        return whitelistEnabled && at != null;
    }
}
